package cn.com.idmy.mq.coder;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

@Slf4j
public class FastjsonMqMsgDecoder implements MqMsgDecoder {

    @Nullable
    @Override
    public <T> T decode(Object msg, Class<T> clazz) {
        if (msg instanceof MessageExt) {
            return decode((MessageExt) msg, clazz);
        } else if (msg instanceof Message) {
            return decode((Message) msg, clazz);
        } else {
            log.warn("message is not MessageExt or Message.");
            return null;
        }
    }

    @Nullable
    public <T> T decode(MessageExt msg, Class<T> type) {
        if (msg == null || msg.getBody() == null) {
            log.warn("message is empty.");
            return null;
        } else {
            try {
                return JSON.parseObject(msg.getBody(), type);
            } catch (Exception e) {
                log.error("parse message json fail : {}", e.getMessage());
                return null;
            }
        }
    }

    @Nullable
    public <T> T decode(Message msg, Class<T> type) {
        if (msg == null || msg.getBody() == null) {
            log.warn("message is empty.");
            return null;
        } else {
            try {
                return JSON.parseObject(msg.getBody(), type);
            } catch (Exception e) {
                log.error("parse message json fail : {}", e.getMessage());
                return null;
            }
        }
    }
}
